package com.tuomaxu.controller;


import com.tuomaxu.pojo.AuthCode;
import com.tuomaxu.service.AuthCodeService;
import com.tuomaxu.service.EmailServiceFeignClient;
import com.tuomaxu.service.UserServiceFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    private AuthCodeService authCodeService;

    @Autowired
    private EmailServiceFeignClient emailService;

    @Autowired
    private UserServiceFeignClient userService;

    @GetMapping("/validate/{email}/{code}")
    public Integer validate(@PathVariable String email,@PathVariable String code){
        AuthCode authCode = new AuthCode();
        authCode.setCode(code);
        authCode.setEmail(email);
        return authCodeService.validateCode(authCode);
    }


    /**
     * 向指定邮箱发送验证码，并将验证码保存在数据库
     * http://localhost:8081/api/code/create/111
     * @param email
     * @return
     */
    @GetMapping("/create/{email}")
    public boolean create(@PathVariable String email){

        //先验证这个邮箱是否已注册，调用user服务

        boolean registered = userService.isRegistered(email);
        if(registered == true){
            return false;
        }

        String code = randomCode();
        AuthCode authCode = new AuthCode();
        authCode.setCode(code);
        authCode.setEmail(email);
        //保存数据库
        boolean b = authCodeService.addCode(authCode);
        if(b == false){
            return false;
        }

//        return true;
        //调用邮件微服务发送验证码
        return emailService.send(email, code);
    }

    public static String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }
}
